package com.rex.editor.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.FrameLayout;

import com.base.common.utils.DensityUtil;
import com.rex.editor.R;
import com.rex.editor.common.CommonJs;
import com.rex.editor.common.FilesUtils;
import com.rex.editor.common.Utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import static com.rex.editor.common.FilesUtils.getVideoThumbnail;

/**
 * @author Rex on 2019/6/20.
 */
public class RichEditorNew extends RichEditor {
    private OnTextChangeNewListener mTextChangeListener;
    private OnConsoleMessageListener mOnConsoleMessageListener;
    /**
     * 用于在ontextchange中执行操作标识避免循环
     */
    private boolean isUnableTextChange = false;
    private boolean isNeedSetNewLineAfter = false;
    //视频缩略图
    private boolean isNeedAutoPosterUrl = false;
    public final static String FILE_TAG = "/rich_editor";


    public RichEditorNew(Context context) {
        super(context);
        initConfig();
    }

    public RichEditorNew(Context context, AttributeSet attrs) {
        super(context, attrs);
        initConfig();
    }

    public RichEditorNew(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initConfig();
    }

    public boolean isNeedAutoPosterUrl() {
        return isNeedAutoPosterUrl;
    }

    //自动为视频添加缩略图
    public void setNeedAutoPosterUrl(boolean needAutoPosterUrl) {
        isNeedAutoPosterUrl = needAutoPosterUrl;
    }

    public void getCurrChooseParams() {
        exec("javascript:RE.getSelectedNode();");
    }

    //不可编辑 预览模式
    public void loadRichEditorCode(String html) {
        loadDataWithBaseURL("file:///android_asset/", html + head + IMG_CLICK_JS, "text/html", "utf-8", null);
    }


    public interface OnTextChangeNewListener {
        void onTextChange(String text);
    }

    public interface OnConsoleMessageListener {
        void onTextChange(String message, int lineNumber, String sourceID);
    }


    public void setOnTextChangeListener(OnTextChangeNewListener listener) {
        this.mTextChangeListener = listener;
    }

    public void setOnConsoleMessageListener(OnConsoleMessageListener listener) {
        this.mOnConsoleMessageListener = listener;
    }

    private void initConfig() {
        setOnTextChangeListener(new OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {

                if (text.equals("<br>")) {
                    insertHtml("<font></font>");
                    return;
                }
                if (isNeedSetNewLineAfter()) {
                    setNewLine();
                }
                if (isUnableTextChange) {
                    isUnableTextChange = false;
                } else {
                    if (mTextChangeListener != null) {
                        mTextChangeListener.onTextChange(text);
                    }
                }

            }
        });
//设置 防止图片太大超出屏幕
        getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setWebChromeClient(new WebChromeClient() {
            @Override
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                super.onConsoleMessage(message, lineNumber, sourceID);
                if (mOnConsoleMessageListener != null) {
                    mOnConsoleMessageListener.onTextChange(message, lineNumber, sourceID);
                }

            }

        });

    }

    //解决图片太大  宽度需要滑动
    public String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%")
                    .attr("height", "auto");
        }
        return doc.toString();
    }


    /**
     * 插入图片
     *
     * @param url
     */
    public void insertImage(String url) {
        insertImage(url, "", "");
    }

    //max-width:100%;height:200px;object-fit:cover;
    @Override
    public void insertImage(String url, String alt, String style) {
        if (TextUtils.isEmpty(style)) {
            alt = "picvision";
            //10px
            style = "margin-top:10px;width:100%;height:200px;object-fit:cover;";
        }
        super.insertImage(url, alt, style);
    }

    /**
     * 插入html格式的文字
     *
     * @param html
     */
    public void insertHtml(String html) {
        exec("javascript:RE.prepareInsert();");
        exec("javascript:RE.insertHTML('" + html + "');");
    }

    /**
     * 插入  @青菜紫红   @某人
     *
     * @param str
     */
    public void insertRemind(String str, String id, String color) {
        insertOnClickText(REMIND, id, str, "@", color);
    }

    /**
     * 插入  #青菜紫红   话题
     * <p>
     * gambit 为参数
     *
     * @param str
     * @param color #3371E8
     */
    public void insertGambit(String str, String id, String color) {
        insertOnClickText(GAMBIT, id, str, "#", color);
    }


    /**
     * 插入可点击的文字
     *
     * @param type
     * @param arguments
     * @param content
     * @param mark
     * @param color     class="android"
     */
    public void insertOnClickText(String type, String arguments, String content, String mark, String color) {
        String html = "<label  name=\"" + type + "\"   data=\"" + arguments + "\"    style=\"color:" + color + "\">" + mark + content + "</label>&nbsp;";
        insertHtml(html);
    }

    /**
     * 插入可点击的文字,赛事
     *
     * @param ids
     * @param matchName
     * @param homeTeam
     * @param guestTeam
     */
    public void insertMatch(String ids, String matchName, String time, String homeTeam, String guestTeam) {
        String html = " <p class=\"android\" name=\"" + MATCHS + "\"  data=" + ids + "  style=\"height:45px;line-height:45px;background: #FEE789;padding:0 15px;\">" +
                "<span style=\"font-weight: normal;\">" + matchName + "</span>" +
                "<span style=\"display: inline-block; height:16px; line-height: 16px; background: #000; color:#fff; text-align: center; margin:0 10px; padding: 5px;\">" + time + "</span>" +
                "<span style=\"font-weight: bold;\">" + homeTeam + "</span>" +
                "<i style=\"font-weight: bold;font-size: 20px;margin:0 10px\">VS</i>" +
                "<span style=\"font-weight: bold;\">" + guestTeam + "</span><span style=\"float: right;\"> > </span>" +
                "</p><br/>";
        setNewLine();
        insertHtml(html);
    }

    /**
     * 换行
     */
    public void setNewLine() {
        isNeedSetNewLineAfter = false;
        isUnableTextChange = true;
        exec("javascript:RE.prepareInsert();");
        exec("javascript:RE.insertHTML('<br></br>');");
    }

    public void setHint(String placeholder) {
        setPlaceholder(placeholder);
    }

    public void setHintColor(String placeholderColor) {
        exec("javascript:RE.setPlaceholderColor('" + placeholderColor + "');");
    }

    public void setNeedSetNewLineAfter(boolean needSetNewLineAfter) {
        isNeedSetNewLineAfter = needSetNewLineAfter;
    }

    public boolean isNeedSetNewLineAfter() {
        return isNeedSetNewLineAfter;
    }


    /**
     * 插入文件
     * richEditor.insertFileWithDown(TEST_VIDEO_URL, "点击下载");
     *
     * @param downloadUrl
     * @param title
     */
    public void insertFileWithDown(String downloadUrl, String title) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return;
        }

        String fileName;
        try {
            String[] split = downloadUrl.split("/");
            fileName = split[split.length - 1];
        } catch (Exception e) {
            fileName = "rich" + System.currentTimeMillis();
        }

        title += fileName;
        insertHtml("<a href=\"" + downloadUrl + "\" download=\"" + fileName + "\">" +
                title +
                "</a><br></br>");
    }

    public void insertAudio(String audioUrl) {
        insertAudio(audioUrl, "");
    }

    /**
     * 插入音频
     *
     * @param audioUrl
     * @param custom
     */
    public void insertAudio(String audioUrl, String custom) {
        if (TextUtils.isEmpty(custom)) {
            custom =             //增加进度控制
                    "controls=\"controls\"" +
                            //宽高
                            "height=\"300\" " +
                            //样式
                            " style=\"margin-top:10px;max-width:100%;\"";
        }
        exec("javascript:RE.prepareInsert();");
        exec("javascript:RE.insertAudio('" + audioUrl + "', '" + custom + "');");
    }

    /**
     * 插入视频
     *
     * @param videoUrl
     */
    public void insertVideo(String videoUrl) {
        insertVideo(videoUrl, "", "");
    }

    /**
     * @param videoUrl
     * @param customStyle
     * @param posterUrl   视频默认缩略图
     */
    public void insertVideo(String videoUrl, String customStyle, String posterUrl) {
        if (TextUtils.isEmpty(customStyle)) {
            customStyle =             //增加进度控制
//                    "controls=\"controls\"" + //已修改到video标签里面
                    //视频显示第一帧
//                            " initial-time=\"0.01\" " +//客户端无效
                    //宽高
                    "height=\"200px\" " +
                            //样式
                            " style=\"margin-top:10px;width:100%;\"";
        }

        if (TextUtils.isEmpty(posterUrl) && isNeedAutoPosterUrl) {
            Bitmap videoThumbnail = getVideoThumbnail(videoUrl);
            if (videoThumbnail != null) {
                String videoThumbnailUrl = FilesUtils.saveBitmap(videoThumbnail);
                if (!TextUtils.isEmpty(videoThumbnailUrl)) {
                    posterUrl = videoThumbnailUrl;
                }
            }

        }


        System.out.println("videoUrl = [" + videoUrl + "], custom = [" + customStyle + "]");
        System.out.println("videoUrl getAbsolutePath = [" + new File(videoUrl).getAbsolutePath() + "]");
        exec("javascript:RE.prepareInsert();");
        exec("javascript:RE.insertVideo('" + videoUrl + "', '" + customStyle + "', '" + posterUrl + "');");
    }


    // 获取html本地的地址 方便上传的时候转为在线的地址
    public List<String> getAllSrcAndHref() {
        return Utils.getHtmlSrcOrHrefList(getHtml());
    }

    //缩略图功能会产生本地文件可调用此方法清理
    public void clearLocalRichEditorCache() {
        FilesUtils.clearLocalRichEditorCache();
    }

}
